<?php
// 创建服务实例，监听端口
$ws = new Swoole\Websocket\Server('0.0.0.0',8080);

// 设置静态路由
$ws->set([
    'enable_static_handler' => true, // 静态路由支持
    'document_root' => __DIR__ . '/public' // 静态文件根目录
]);

// 监听连接事件
$ws->on('open', function ($ws, $request){
    // 连接成功 服务器主动发起消息
    echo "{$request->fd} is comming \n";
    $ws->push($request->fd, "hello");
});

// 监听消息事件
$ws->on('message', function ($ws, $frame){
    echo "message: {$frame->data} \n";
    if (is_numeric($frame->data)) {
        $ws->push($frame->fd, $frame->data + 1);
    }
});

// 监听关闭事件
$ws->on('close', function ($ws, $fd){
    echo "client {$fd} closed \n";
});

$ws->start();